<template>
  <div class="register-page">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back-btn" @click="handleBack">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </div>
      <div class="hospital-name">{{ hospitalInfo.hospitalName }}</div>
    </div>

    <!-- 医院基本信息 -->
    <div class="hospital-info">
      <div class="hospital-title">{{ hospitalInfo.hospitalName }}</div>
      <div class="hospital-details">
        <span class="level">{{ getLevelText(hospitalInfo.grade) }}</span>
        <span class="separator">|</span>
        <span class="type">{{ getHospitalTypeText(hospitalInfo.hospitalType) }}</span>
        <span class="separator">|</span>
        <span class="insurance">医保无需定点</span>
      </div>
      <div class="hospital-address">
        <el-icon><Location /></el-icon>
        {{ getFullAddress(hospitalInfo) }}
      </div>
    </div>

    <div class="divider"></div>

    <!-- 全部科室 -->
    <div class="departments-section">
      <div class="section-title">全部科室</div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <!-- 科室列表 -->
      <div v-else class="departments-list">
        <div
            v-for="primaryDept in primaryDepartments"
            :key="primaryDept.departmentId"
            class="department-group"
        >
          <div class="primary-department" @click="toggleSecondaryDept(primaryDept.departmentId)">
            <div class="primary-name">{{ primaryDept.departmentName }}</div>
            <div class="arrow" :class="{ expanded: expandedDept === primaryDept.departmentId }">
              <el-icon><ArrowDown /></el-icon>
            </div>
          </div>

          <!-- 二级科室 -->
          <div
              v-if="expandedDept === primaryDept.departmentId"
              class="secondary-departments"
          >
            <div
                v-for="secondaryDept in getSecondaryDepartments(primaryDept.departmentId)"
                :key="secondaryDept.departmentId"
                class="secondary-department"
                @click="handleSelectDepartment(secondaryDept)"
            >
              {{ secondaryDept.departmentName }}
            </div>

            <!-- 二级科室加载状态 -->
            <div v-if="loadingSecondaryDept === primaryDept.departmentId" class="secondary-loading">
              <el-skeleton :rows="2" animated />
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="primaryDepartments.length === 0" class="empty-state">
          <el-empty description="暂无科室数据" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Location, ArrowDown } from '@element-plus/icons-vue'
import { getHospital } from '@/api/institution/hospital.js'
import { listPrimaryDepartments, listChildrenDepartments } from '@/api/institution/hospital.js'


const router = useRouter()
const route = useRoute()

const hospitalId = ref('')
const hospitalInfo = ref({})
const loading = ref(false)
const loadingSecondaryDept = ref(null)
const primaryDepartments = ref([])
const secondaryDepartmentsMap = ref({})
const expandedDept = ref(null)

// 页面加载时初始化数据
onMounted(() => {
  hospitalId.value = route.params.hospitalId
  loadHospitalData()
  loadPrimaryDepartments()
})

// 加载医院数据
const loadHospitalData = async () => {
  try {
    const response = await getHospital(hospitalId.value)
    hospitalInfo.value = response.data || {}
  } catch (error) {
    console.error('加载医院数据失败:', error)
    ElMessage.error('加载医院数据失败')
  }
}

// 加载一级科室
const loadPrimaryDepartments = async () => {
  try {
    loading.value = true
    const response = await listPrimaryDepartments()
    primaryDepartments.value = response.data || response.rows || []
  } catch (error) {
    console.error('加载一级科室失败:', error)
    ElMessage.error('加载科室数据失败')
    primaryDepartments.value = []
  } finally {
    loading.value = false
  }
}

// 切换二级科室显示
const toggleSecondaryDept = async (departmentId) => {
  if (expandedDept.value === departmentId) {
    expandedDept.value = null
    return
  }

  expandedDept.value = departmentId

  // 如果还没有加载过该一级科室的二级科室，则加载
  if (!secondaryDepartmentsMap.value[departmentId]) {
    await loadSecondaryDepartments(departmentId)
  }
}

// 加载二级科室
const loadSecondaryDepartments = async (parentId) => {
  try {
    loadingSecondaryDept.value = parentId
    const response = await listChildrenDepartments(parentId)
    secondaryDepartmentsMap.value[parentId] = response.data || response.rows || []
  } catch (error) {
    console.error('加载二级科室失败:', error)
    ElMessage.error('加载二级科室失败')
    secondaryDepartmentsMap.value[parentId] = []
  } finally {
    loadingSecondaryDept.value = null
  }
}

// 获取二级科室
const getSecondaryDepartments = (parentId) => {
  return secondaryDepartmentsMap.value[parentId] || []
}

// 选择科室
const handleSelectDepartment = (department) => {
  console.log('跳转参数:', {
    hospitalId: hospitalId.value,
    departmentId: department.departmentId,
    departmentName: department.departmentName
  })

  // 跳转到医生排班页面
  router.push({
    path: `/medical/doctors/${hospitalId.value}/${department.departmentId}`,
    query: {
      departmentName: department.departmentName
    }
  })
}

// 获取完整地址
const getFullAddress = (hospital) => {
  if (!hospital) return '地址未知'

  const { province, city, district, address } = hospital
  const addressParts = []

  if (province) addressParts.push(province)
  if (city) addressParts.push(city)
  if (district) addressParts.push(district)
  if (address) addressParts.push(address)

  return addressParts.length > 0 ? addressParts.join('') : '地址未知'
}

// 获取机构类型显示文本
const getHospitalTypeText = (type) => {
  if (!type) return '医疗机构'

  const typeMap = {
    1: '医院',
    2: '体检中心',
    3: '诊所'
  }

  return typeMap[type] || type || '医疗机构'
}

// 获取机构等级显示文本
const getLevelText = (grade) => {
  if (!grade) return '医疗机构'

  const gradeStr = grade.toString()
  const levelTextMap = {
    '3a': '三级甲等',
    '三级甲等': '三级甲等',
    '2a': '二级甲等',
    '二级甲等': '二级甲等',
    '1a': '一级甲等',
    '一级甲等': '一级甲等',
    '3b': '三级乙等',
    '三级乙等': '三级乙等',
    '2b': '二级乙等',
    '二级乙等': '二级乙等',
    '1b': '一级乙等',
    '一级乙等': '一级乙等'
  }

  return levelTextMap[gradeStr] || gradeStr || '医疗机构'
}

// 返回上一页
const handleBack = () => {
  router.back()
}
</script>

<style scoped lang="scss">
.register-page {
  min-height: 100vh;
  background: #f8f9fa;
}

// 顶部导航
.header {
  background: white;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-bottom: 1px solid #f0f0f0;

  .back-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 14px;
    color: #409eff;
    cursor: pointer;

    &:hover {
      opacity: 0.8;
    }
  }

  .hospital-name {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

// 医院基本信息
.hospital-info {
  background: white;
  padding: 16px;

  .hospital-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .hospital-details {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    margin-bottom: 8px;

    .level {
      color: #f56c6c;
      font-weight: 500;
    }

    .type {
      color: #666;
    }

    .insurance {
      color: #67c23a;
    }

    .separator {
      color: #ddd;
    }
  }



  .hospital-address {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 13px;
    color: #999;
  }
}

// 分隔线
.divider {
  height: 8px;
  background: #f0f2f5;
}

// 科室区域
.departments-section {
  background: white;
  padding: 16px;

  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 16px;
    padding-left: 8px;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background: #409eff;
      border-radius: 2px;
    }
  }
}

// 加载状态
.loading-container {
  padding: 20px 0;
}

// 空状态
.empty-state {
  padding: 40px 0;
}

// 科室列表
.departments-list {
  .department-group {
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }
  }

  .primary-department {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    cursor: pointer;

    .primary-name {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .arrow {
      transition: transform 0.3s ease;

      &.expanded {
        transform: rotate(180deg);
      }

      .el-icon {
        color: #999;
      }
    }

    &:hover {
      background: #f8f9fa;
      margin: 0 -16px;
      padding: 16px;
    }
  }

  .secondary-departments {
    background: #f8f9fa;
    margin: 0 -16px;
    padding: 0 16px;

    .secondary-department {
      padding: 12px 0;
      border-bottom: 1px solid #e8e8e8;
      font-size: 14px;
      color: #666;
      cursor: pointer;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        color: #409eff;
        background: white;
        margin: 0 -16px;
        padding: 12px 16px;
      }
    }

    .secondary-loading {
      padding: 12px 0;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .header {
    padding: 12px;
  }

  .hospital-info {
    padding: 12px;

    .hospital-title {
      font-size: 16px;
    }

    .hospital-details {
      font-size: 13px;
    }

    .hospital-stats {
      font-size: 12px;
    }

    .hospital-address {
      font-size: 12px;
    }
  }

  .departments-section {
    padding: 12px;

    .section-title {
      font-size: 16px;
    }
  }

  .departments-list {
    .primary-department {
      padding: 12px 0;

      .primary-name {
        font-size: 15px;
      }

      &:hover {
        margin: 0 -12px;
        padding: 12px;
      }
    }

    .secondary-departments {
      margin: 0 -12px;
      padding: 0 12px;

      .secondary-department:hover {
        margin: 0 -12px;
        padding: 12px;
      }
    }
  }
}
</style>